import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Труба черная ТЭСЦ-3'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        try:
            product = row["Первичный продукт"]
            diametr = row["Диаметр, мм <Производство>"]
            thickness = row["Толщина стенки, мм <Производство>"]
            gmsps = row["ГМСПС"]
            en_pr=None
            if "ТУ" in str(row["НТД качества (трубы стальные) <Производство>"]) or "ГОСТ" in str(row["НТД качества (трубы стальные) <Производство>"]):
                en_pr="ПР"
            else:
                if pd.notna(row["НТД качества (трубы стальные) <Производство>"]):
                    en_pr="EN"
            diametr_led = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-3",
                f"`Производство`=='Труба черная ТЭСЦ-3' and `Продукт`=='{product}'",
                "Доп параметр1",
                diametr,
                "Доп параметр1"
                )
            diametr_led_s=str(diametr_led).replace(".0","")
            thickness_range = consolidator.scalar_in_guid("Параметры по Продукту ТЭСЦ-3",
                f"`Производство`=='Труба черная ТЭСЦ-3' and `Продукт`=='{product}' and {thickness}>=`Мин` and {thickness}<=`Макс` and `Доп параметр2`.str.contains('{gmsps}')",
                "Диапазон")
            print(f"product: {product}; diametr: {diametr}; thickness: {thickness}; gmsps: {gmsps}; en_pr: {en_pr}; diametr_led: {diametr_led}; thickness_range: {thickness_range}")
            product_up = f"{product}{diametr_led_s} {gmsps}"

            ###### П0130_Наименование_УП_для_труб ###########
            if pd.notna(gmsps) and "ГУ" in gmsps:
                product_up=f"{product}{diametr_led_s} {thickness_range} {gmsps}"
                if en_pr=="EN" and "ПР" in gmsps: product_up=product_up +" EN"
            if pd.notna(gmsps) and "ГК" in gmsps:
                product_up=f"{product}{diametr_led_s} {gmsps}"
                if en_pr=="EN" and "ПР" in gmsps: product_up=product_up +" EN"
            if diametr_led==457 and "EN" not in product_up: product_up = product_up+" EN"
            #################################################

            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__pipe_black_t3__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

